package com.sds.sweng.swat.miplatform.ui.design.models.area.sub;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import org.eclipse.ui.views.properties.PropertyDescriptor;

import com.sds.sweng.swat.miplatform.ui.design.models.component.MButton;
import com.sds.sweng.swat.miplatform.ui.design.utils.CloneUtils;
import com.sds.sweng.swat.miplatform.ui.design.utils.FontUtils;

public class TitleSubArea extends SubArea {

	public static final int GAP = 3;

	public static final String
		TITLE = "title",
		BUTTONS = "buttons";

	static {
		descriptors = new IPropertyDescriptor[] {
			new PropertyDescriptor(TITLE, "Title"),
			new PropertyDescriptor(BUTTONS, "Buttons")
		};
	}

	private String title = StringUtils.EMPTY;

	public TitleSubArea() {

	}

	public String getTitle() {
		return title;
	}

	public TitleSubArea clone() {
		TitleSubArea clone = (TitleSubArea) super.clone();
		clone.setTitle(getTitle());
		clone.setButtons(CloneUtils.clone(getButtons()));

		return clone;
	}

	public void setTitle(String title) {
		this.title = title;

		firePropertyChange(TITLE, null, title);
	}

	@JsonIgnore
	public List getButtons() {
		return getChildren();
	}

	@JsonIgnore
	public void setButtons(List<MButton> buttons) {
		removeChildren();

		for (int i=0;i<buttons.size();i++) {
			addChild(buttons.get(i));
		}

		firePropertyChange(BUTTONS, null, buttons);
	}

	public Object getPropertyValue(Object id) {
		if (TITLE.equals(id))
			return getTitle();
		else if (BUTTONS.equals(id))
			return getButtons();

		return null;
	}

	public void setPropertyValue(Object id, Object value) {
		if (TITLE.equals(id))
			setTitle((String) value);
		else if (BUTTONS.equals(id))
			setButtons((List<MButton>) value);
	}

	@Override
	public boolean isEmpty() {
		if (StringUtils.isNotEmpty(getTitle()) || getButtons().size() > 0)
			return false;

		return true;
	}

	@Override
	public int getRemainWidth() {
		int remainWidth = getWidth();
		remainWidth -= getTitleWidth(getTitle());

		for (int i=0;i<getButtons().size();i++) {
			remainWidth -= ((MButton) getButtons().get(i)).getWidth();
			remainWidth -= GAP;
		}

		return 0;
	}

	private int getTitleWidth(String text) {
		if (StringUtils.isEmpty(text))
			return 0;
		else
			return 15 + FontUtils.getTextWidth(text, FontUtils.TITLE_FONT);
	}

	@Override
	public int getRequireWidth() {
		int requireWidth = getTitleWidth(getTitle());

		for (int i=0;i<getButtons().size();i++) {
			MButton button = (MButton) getButtons().get(i);
			requireWidth += button.getWidth();
			requireWidth += GAP;
		}

		return requireWidth;
	}
}
